jQuery(document).ready(function(){
	$.setDateController(type);		//set times
	var  gridDatas, $form = $('#scopeSearch');		//form
	//buttons
	$('#exportBtn').click(function(){			//导出报表
		window.location.href = "report.xls";
	}).button({ disabled: true });
	
	$('#printBtn').click(function(){		//打印报表
		window.open("report.pdf");
	}).button({ disabled: true });
	
	$('#genChartBtn').click(function(){		//生成图表
		$('#container').dialog('open');
	}).button({ disabled: true });
	
	$('#collapse').click(function(){			//收展
		$('#queryItems').toggle('slow');
		var isCol = $(this).attr('data');
		if (isCol == 'true') {
			$(this).val("收起查询条件");
			$(this).attr('data', 'false');
		} else {
			$(this).val("展开查询条件");
			$(this).attr('data', 'true');
		}
	}).button();
	
	//报表
	//formatter
 	var formatFunc = function(data, options, rowObject) {
 		var value;
		if (data) {
			if (typeof data != 'object') {
				value = data;
				if (!isNaN(data.value))
					value = new Number(data).toFixed(2);
				return value;
			}
			value = data.value;
			if (!isNaN(data.value))
				value = new Number(data.value).toFixed(2);
			
			if (!data.flag) return value;
			var flag = $.trim(flags[data.flag]);
			var clz = flag == 'HL' ? 'exceed' : 'exception';
			if (!flag || !flag.showNum || $.trim(flag.showNum) == 'T') 
				return $.format('<span title="{0}" class="{1}">{2}</span>', flag.desp, clz, value + ' - ' + data.flag);
			return $.format('<span title="{0}" class="{1}">{2}</span>', value, clz, flag.desp);
		}
		return "-";
	};

	//表格
	var $gridTable;
	
	$('#genTableBtn').button().click(function(){
		$('#grid').setLoading();
		var $site = $('#site'),
			site = $site.val(),
			siteText = $site.find('option[value='+site+']').text(),
			$items = $('#items_' + site), 
			$sItems = $items.find('input[type=checkbox]:checked'), 
			options = {
				caption:"报表",
				report: true,
				footerrow : true,
				userDataOnFooter : true,
				gridComplete: function() {
					$.genTableTip(flags);
				},
				datatype: 'json',
				url: 'data',
				mtype: 'post'
			}, headerNames = [{
				startColumnName: 'time', numberOfColumns: 1, titleText: '时间'
			}], colNames = [""],
			colModel = [{name:'time',index:'time',align:'center',sortable:false}], 
			colIndexes = [];
		
		//config grid
		$sItems.each(function(index, item){
			headerNames.push({
				startColumnName:$(item).attr("item"), 
				numberOfColumns:1, 
				titleText:item.title
			});
			colNames.push($(item).attr("unit"));
			colIndexes.push($(item).attr("item"));
			colModel.push({
				name: $(item).attr('item'), 
				index: $(item).attr('item'), 
				width: '68px',
				align:'center',
				formatter: formatFunc,
				sortable:false
			});
		});
		options = $.extend(options, {
			groupHeaders: headerNames,
			colNames: colNames,
			colModel: colModel
		});
		
		//config chart
		var colIndexes=['time'], headerNames = ["时间"], 
			x_cats = [], series = [], itemIds = [], siteItems = [],
			tempIndexes, tempNames;
		$sItems.each(function(index, item){
			headerNames.push(item.title);
			colIndexes.push($(item).attr('item'));
			itemIds.push({
				name: 'itemIds',
				value: $(item).attr('item')
			});
			siteItems.push({
				name: 'siteItems',
				value: item.value
			});
			//colIndexes.push(item.value);
		});
		
		options.tempIndexes = tempIndexes = colIndexes.slice(1);
		options.tempNames = tempNames = headerNames.slice(1);
		
		options.postData = $.array2obj($form.serializeArray().concat(itemIds).concat(siteItems));
		options.gridFormComplete = function() {
			//query data
			$.ajax({
				url: $form.attr('action'),
				type: $form.attr('method'),
				dataType: 'json',
				data: $form.serializeArray().concat(itemIds).concat(siteItems), 
				success: function(datas){
					gridDatas = datas;
					var bodys = gridDatas.bodys, footers = gridDatas.footers;
					$gridTable.setFooterDatas(footers);
					
					$('#exportBtn').button({ disabled: false });
					$('#printBtn').button({ disabled: false });
					$('#genChartBtn').button({ disabled: false });
				}
			});
		};
		
		options.loadComplete = function(chartOpts) {
			var width = 100 * chartOpts.x_cats.length;
			chart = $('#container').genLineChart($.extend({
				title: '每小时报表',
				subtitle: $.format('<b>站点：{0}</b>时间：{1} ~ {2}',siteText, $('#startDate').val(), $('#endDate').val()),
				ytitle: '监测值',
				width: width
			}, chartOpts));
			$('#container>div').css({margin: '0 auto'});
		};
		
		$gridTable = $('#grid').genGrid(options);
	});
	
	$('#site').change(function(){			//站点下拉框
		$('.item-ul').hide();
		$('#items_' + this.value).show();
		$('#genTableBtn').click();
	});
	$('#site').change();
	
	$('#container').css({
		'overflow-x': 'auto'
	}).dialog({
		autoOpen: false,
		width: '100%',
		height: 480
	});
});